package cn.schoolwow.util.domain.crypto.messageDigest;

import cn.schoolwow.quickflow.QuickFlow;
import cn.schoolwow.quickflow.QuickFlowBuilder;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.util.module.crypto.messageDigest.domain.MessageDigestOption;
import cn.schoolwow.util.module.crypto.messageDigest.flow.GetMessageDigestHexFlow;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**消息散列算法*/
public class MessageDigest {
    private MessageDigestOption messageDigestOption = new MessageDigestOption();

    private QuickFlow quickFlow = QuickFlowBuilder.newInstance()
            .putContextThreadLocalInstanceData(messageDigestOption);

    public static MessageDigest newMessageDigest(){
        MessageDigest messageDigest = new MessageDigest();
        return messageDigest;
    }

    /**指定散列算法*/
    public MessageDigest messageDigestType(MessageDigestType messageDigestType){
        messageDigestOption.messageDigestType = messageDigestType;
        return this;
    }

    /**指定数据*/
    public MessageDigest data(byte[] data){
        messageDigestOption.data = data;
        return this;
    }

    /**指定数据*/
    public MessageDigest data(String data){
        messageDigestOption.data = data.getBytes(StandardCharsets.UTF_8);
        return this;
    }

    /**指定文件*/
    public MessageDigest file(File file){
        messageDigestOption.file = file;
        return this;
    }

    /**获取散列值*/
    public String getHexString(){
        FlowContext flowContext = quickFlow.startFlow(new GetMessageDigestHexFlow())
                .putCurrentCompositeFlowData("type", "data")
                .execute();
        String digest = flowContext.checkData("string", String.class);
        return digest;
    }

    /**获取文件散列值*/
    public String getFileHexString(){
        FlowContext flowContext = quickFlow.startFlow(new GetMessageDigestHexFlow())
                .putCurrentCompositeFlowData("type", "file")
                .execute();
        String digest = flowContext.checkData("string", String.class);
        return digest;
    }

}
